package com.demo.main.controller;

import com.demo.main.dao.MessageDao;
import com.demo.main.entity.Message;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@WebServlet(urlPatterns = "/SaveMessageServlet")
public class SaveMessageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String username = request.getParameter("username");
            String content = request.getParameter("content");
              String timestampStr = request.getParameter("timestamp");
            LocalDateTime timestamp = null;
            if (timestampStr == null || timestampStr.isEmpty()) {
                // 时间戳字段为空，使用当前时间戳
                timestamp = LocalDateTime.now();
            } else {
                // 将时间戳字符串解析为 LocalDateTime 对象
                timestamp = LocalDateTime.parse(timestampStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            Message message = new Message();
            message.setUsername(username);
            message.setContent(content);
            message.setTimestamp(timestamp);

            MessageDao messageDao = new MessageDao();
            messageDao.addMessage(message);

            response.sendRedirect("/router?page=view_messages");
        } catch (SQLException e) {
            request.setAttribute("errorMessage", "Error: " + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/views/view_messages.jsp").forward(request, response);
        }
    }
}
